package com.zofer.study;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ForkJoinTest extends RecursiveTask {
    int start;
    int end;

    public ForkJoinTest(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Object compute() {
        //创建子任务
        List<ForkJoinTask<Integer>> lt = new ArrayList<>();
        int m = 2000, s = start, e = end, r = 0;
        do {
            if (e - s <= m){
                for (int i = s; i < e; i++) {
                    r += i;
                }
                System.out.println("Sum:"+r+", start:"+s+"~end:"+e);
            }else {
                e = Math.min(s + m - 1,e);
                lt.add(new ForkJoinTest(s,e).fork());
            }
            s = e + 1;
            e = end;
        }while (s < e);

        //合并子任务结果
        for (ForkJoinTask<Integer> ft:lt){
            r += ft.join();
        }
        return r;
    }


    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Future<Integer> future = forkJoinPool.submit(new ForkJoinTest(0,10000));
        try {
            System.out.println("ForkJoin Return:"+future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
